package com.zyf.pattern.proxy.custom;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.lang.reflect.Field;

/**
 * 自定义类加载器
 * create by yifeng
 */
public class CClassLoader extends ClassLoader{

    private File classPathfile;
    public CClassLoader() {
        String path = CClassLoader.class.getResource("").getPath();
        this.classPathfile = new File(path);

    }

    @Override
    protected Class<?> findClass(String name) {
        String className = CClassLoader.class.getPackage().getName() + "." + name;
        if (classPathfile != null) {
            File classFile = new File(classPathfile, name.replaceAll("\\.", "/") + ".class");
            if (classFile.exists()) {
                try(FileInputStream in = new FileInputStream(classFile);
                    ByteArrayOutputStream out = new ByteArrayOutputStream();){
                    byte[] buff = new byte[1024];
                    int len;
                    while ((len = in.read(buff)) != -1) {
                        out.write(buff, 0, len);
                    }
                    return defineClass(className, out.toByteArray(), 0, out.size());
                }
                catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
}
